/**
 * Copyright (c) 1987-2010 Fujian Fujitsu Communication Software Co., 
 * Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of 
 * Fujian Fujitsu Communication Software Co., Ltd. 
 * ("Confidential Information"). You shall not disclose such 
 * Confidential Information and shall use it only in accordance with 
 * the terms of the license agreement you entered into with FFCS.
 *
 * FFCS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. FFCS SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */
package com.xhui.vimarket.common.utils.collection.impl;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 组合迭代器，用于组合两个Iterator，顺序执行迭代。
 * 并发增删操作控制，由各自Iterator决定执行动作。
 */
public class CompositeIterator<E> extends Object implements Iterator<E> {
    /**
     * 日志记录器。
     */
    private static final Logger LOG = LoggerFactory.getLogger(CompositeIterator.class);
    
    /**
     * 初始元素的Iterator。
     */
    private Iterator<E> retainIterator;
    /**
     * 添加要素的Iterator。
     */
    private Iterator<E> additionIterator;
    /**
     * 是否正在对初始集合进行迭代。
     */
    private boolean isRetainIterator;
    
    /**
     * 组合迭代器的构造函数。
     * 
     * @param retainIterator 初始迭代器
     * @param additionIterator 新增迭代器
     */
    CompositeIterator(Iterator<E> retainIterator, Iterator<E> additionIterator) {
        this.retainIterator = retainIterator;
        this.additionIterator = additionIterator;
        this.isRetainIterator = true;
    }
    
    @Override
    public boolean hasNext() {
        if (this.isRetainIterator) {
            boolean hasNext = this.retainIterator.hasNext();
            if (hasNext) {
                return hasNext;
            } else {
                this.isRetainIterator = false;
            }
        }
        return this.additionIterator.hasNext();
    }

    @Override
    public E next() {
        if (this.isRetainIterator) {
            try {
                return this.retainIterator.next();
            } catch (Exception e) {
                LOG.info("CrmHashSet retain iterator next() is null.");
            }
            this.isRetainIterator = false;
        }
        if (this.additionIterator.hasNext()){
            return this.additionIterator.next();
        }
        return null;
    }

    @Override
    public void remove() {
        if (this.isRetainIterator) {
            this.retainIterator.remove();
        } else {
            this.additionIterator.remove();
        }
    }

    
}
